package com.net.wanjian.networkhospitalmanager.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.net.wanjian.networkhospitalmanager.R;
import com.net.wanjian.networkhospitalmanager.activity.base.BaseActivity;
import com.net.wanjian.networkhospitalmanager.bean.SignCodeDataBean;
import com.net.wanjian.networkhospitalmanager.bean.SignResultBean;
import com.net.wanjian.networkhospitalmanager.consts.ErrorCodeReturn;
import com.net.wanjian.networkhospitalmanager.fragment.HomeFragment;
import com.net.wanjian.networkhospitalmanager.fragment.MyFragment;
import com.net.wanjian.networkhospitalmanager.net.HttpUtil;
import com.net.wanjian.networkhospitalmanager.netstatus.NetUtils;
import com.net.wanjian.networkhospitalmanager.utils.Base64Utils;
import com.net.wanjian.networkhospitalmanager.utils.DateUtil;
import com.net.wanjian.networkhospitalmanager.utils.SharedXmlUtil;
import com.net.wanjian.networkhospitalmanager.utils.ToastUtil;
import com.net.wanjian.networkhospitalmanager.utils.URLDecoderUtil;

import java.util.Date;

import butterknife.BindView;
import io.reactivex.observers.DisposableObserver;

/**
 * Description:应用主页 加载fragment
 * Created by lidongcai on 2017/4/22.
 * Email:  lidongcaiocc@163.com
 */
public class MainActivity extends BaseActivity implements View.OnClickListener {
    public static MainActivity mainActivityInstance = null;
    @BindView(R.id.main_framelayout)
    FrameLayout mainFramelayout;
    @BindView(R.id.main_home_iv)
    ImageView mainHomeIv;
    @BindView(R.id.main_home_tv)
    TextView mainHomeTv;
    @BindView(R.id.main_home_layout)
    LinearLayout mainHomeLayout;
    @BindView(R.id.main_my_iv)
    ImageView mainMyIv;
    @BindView(R.id.main_my_tv)
    TextView mainMyTv;
    @BindView(R.id.main_my_layout)
    LinearLayout mainMyLayout;
    private Fragment[] fragments;
    private ImageView[] imageViews;
    private TextView[] textViews;
    private View[] Layouts;
    private FragmentManager fragmentManager;

    private int lastTag = -1;
    private String eventID;
    private String qrCodeType;
    private String eventType;

    @Override
    protected void initData() {

       /* CustomPushNotificationBuilder builder = new
                CustomPushNotificationBuilder(MainActivity.this,
                R.layout.customer_notitfication_layout,
                R.id.icon,
                R.id.title,
                R.id.text);
        // 指定定制的 Notification Layout
        builder.statusBarDrawable = R.mipmap.logo_app;
        // 指定最顶层状态栏小图标
        builder.layoutIconDrawable = R.mipmap.logo_app;
        // 指定下拉状态栏时显示的通知图标
        JPushInterface.setPushNotificationBuilder(0,builder);*/


        mainActivityInstance = this;
//        NetStateReceiver.registerNetworkStateReceiver(this);
        fragmentManager = getSupportFragmentManager();

        fragments = new Fragment[2];
        fragments[0] = HomeFragment.getInstance();
        fragments[1] = MyFragment.getInstance();

        imageViews = new ImageView[2];
        imageViews[0] = mainHomeIv;
        imageViews[1] = mainMyIv;

        textViews = new TextView[2];
        textViews[0] = mainHomeTv;
        textViews[1] = mainMyTv;

        Layouts = new View[2];
        Layouts[0] = mainHomeLayout;
        Layouts[1] = mainMyLayout;

        for (int i = 0; i < Layouts.length; i++) {
            Layouts[i].setTag(i);
            Layouts[i].setOnClickListener(this);
        }

        setCurrent(0);
    }

    /**
     * 选中tag切换fragment
     *
     * @param tag
     */
    private void setCurrent(int tag) {
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        if (tag == lastTag) return;

        if (!fragments[tag].isAdded()) {
            fragmentTransaction.add(mainFramelayout.getId(), fragments[tag]);
        }
        fragmentTransaction.show(fragments[tag]);
        if (lastTag != -1) {
            fragmentTransaction.hide(fragments[lastTag]);
        }
        fragmentTransaction.commit();

        textViews[tag].setTextColor(getResources().getColor(R.color.colorMain));
        imageViews[tag].setSelected(true);
        if (lastTag != -1) {
            textViews[lastTag].setTextColor(Color.parseColor("#777777"));
            imageViews[lastTag].setSelected(false);
        }
        lastTag = tag;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void onNetworkConnected(NetUtils.NetType type) {

    }

    @Override
    protected void onNetworkDisConnected() {

    }

    private long firstTime;

    @Override
    public void onBackPressed() {
        if (firstTime + 2000 > System.currentTimeMillis()) {
            super.onBackPressed();
            exit();
        } else {
            Toast.makeText(this, "亲，您再按一次我就会退出哦丷丷", Toast.LENGTH_SHORT).show();
        }
        firstTime = System.currentTimeMillis();
    }

    @Override
    public void onClick(View v) {
        int tag = (int) v.getTag();
        setCurrent(tag);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if (result != null) {
            if (result.getContents() == null || !result.getContents().contains("WANJIAN^EVENTSIGN^")) {
                //弹出提示
                ToastUtil.showToast("扫描失败,请重新扫描");

            } else {

                String fromBase64 = Base64Utils.getFromBase64(result.getContents().split("\\^")[2]);
                String decoder = URLDecoderUtil.getDecoder(fromBase64);
                Gson gson = new Gson();
                SignCodeDataBean signCodeDataBean = gson.fromJson(decoder, new TypeToken<SignCodeDataBean>() {
                }.getType());
                eventID = signCodeDataBean.getEventID();
                qrCodeType = signCodeDataBean.getQRCodeType();
                eventType = signCodeDataBean.getEventType();
                String eventSignInStartTime = signCodeDataBean.getEventSignInStartTime();
                String eventSignOutEndTime = signCodeDataBean.getEventSignOutEndTime();
                Date date = DateUtil.getDate();
                long time = date.getTime();
                long timeX = DateUtil.Convert(eventSignInStartTime);
                long timeY = DateUtil.Convert(eventSignOutEndTime);
                //  if (timeX < time && time < timeY) {

                HttpUtil.ScanSign(qrCodeType, eventType, eventID, SharedXmlUtil.getInstance().getUserIdentityId(), SharedXmlUtil.getInstance().getDeviceId(), SharedXmlUtil.getInstance().getToken(), SharedXmlUtil.getInstance().getHospitalId(), new DisposableObserver<SignResultBean>() {

                    @Override
                    public void onNext(SignResultBean signResultBean) {

                        if (signResultBean.getResult().equals(ErrorCodeReturn.success + "")) {
                            SignResultBean.DataBean eventInfo = signResultBean.getData();
                            Intent intent = new Intent(MainActivity.this, SignActivity.class);
                            Bundle mBundle = new Bundle();
                            mBundle.putSerializable("signResultBean", eventInfo);
                            mBundle.putString("qrCodeType", qrCodeType);
                            mBundle.putString("eventID", eventID);
                            mBundle.putString("eventType", eventType);
                            intent.putExtras(mBundle);
                            startActivity(intent);

                        }
                    }

                    @Override
                    public void onError(Throwable throwable) {
                        ToastUtil.showToast("扫码时间不在有效范围内");
                    }

                    @Override
                    public void onComplete() {

                    }
                });

//                } else {
//                    //二维码失效
//                    ToastUtil.showToast("扫码时间不在有效效内");
//                }

            }
        }else {
            super.onActivityResult(requestCode,resultCode,data);
        }
    }
}
